import axios from 'axios'
const cartModule = {
    namespaced: true,
    state(){
        return {
            goodsList: []
        }
    },
    mutations: {
        setGoodsList(state, newList){
            // console.log(newList);
            state.goodsList = newList
        },
        // 每个产品的goods_state选中状态绑定checked
        changeAll(state,obj){
            state.goodsList[obj.index].goods_state = obj.checked;
        },
        // 全选框选中后，将其他产品选中
        setGoodsListState(state, checked){
            state.goodsList.forEach(obj => obj.goods_state = checked)
        },
        addCount(state,index){
            // console.log(state.goodsList);
            state.goodsList[index].goods_count ++
        },
        redCount(state,index){
            state.goodsList[index].goods_count --
        }
    },
    actions: {
        async asyncSetGoodsList(store){
            // 1.发送axios请求
            let res = await axios({
                url: 'https://www.escook.cn/api/cart'
            })
            // console.log(res);
            // 2.后台响应的数据 commit到setGoodsList mutations中
            // console.log(res);
            store.commit('setGoodsList',res.data.list)
        }
    },
    getters: {
        totalCount(state){
            return state.goodsList.reduce((sum, obj) =>{
                if (obj.goods_state === true) {
                    sum += obj.goods_count
                }
                return sum
            }, 0)
        },
        totalPrice(state){
            return state.goodsList.reduce((sum, obj) =>{
                if (obj.goods_state === true) {
                    sum += obj.goods_count * obj.goods_price
                }
                return sum
            }, 0)
        },
        // 小选框控制全选是否选中
        isAllChecked(state){
            return state.goodsList.every(obj => obj.goods_state === true)
        }
    },
    modules: {
        
    }
}

export default cartModule